package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func formatAsDate(t time.Time) string {
	year, month, day := t.Date()
	return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}

func main() {

	InitValidator()

	router := InitRouter()
	router2 := InitRouter2()

	//访问需要使用 example1.com域名访问，端口号默认443， 证书在CA不存在，访问不通
	//CA验证网站："https://acme-v02.api.letsencrypt.org/acme/authz-v3/101454901397
	//autotls.Run(router, "example1.com", "example2.com")

	//m := autocert.Manager{
	//	Prompt:     autocert.AcceptTOS,
	//	HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
	//	Cache:      autocert.DirCache("/var/www/.cache"),
	//}
	//log.Fatal(autotls.RunWithManager(router, &m))

	//优雅重启或者停止
	srv := &http.Server{
		Addr:           ":9080",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	srv2 := &http.Server{
		Addr:           ":9081",
		Handler:        router2,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		//服务连接
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s \n", err)
		}
	}()

	go func() {
		//服务连接
		if err := srv2.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s \n", err)
		}
	}()

	//等待中断信号以优雅的关闭服务器（设置5秒钟超时时间）
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit

	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown: ", err)
	}
	log.Println("Server exiting")

}
